<script lang="ts" setup>
import { set } from '@vueuse/core'
import MarkDownEditor from '@/components/MarkDownEditor/index.vue'
import MyApp from '@/components/MyApp/index.vue'
import type { FormInstance } from '@arco-design/web-vue/es/form'
import AppUpload from '@/components/AppUpload/index.vue'
import { fetchArticle, fetchBackendData, fetchTagsData } from '@/api'
import { notificationSuccess, notificationError } from '@/utils'
import { useRoute } from 'vue-router'
import { ProjectName } from '@/config/constants'

const modelForm = reactive({
  id: 0,
  userId: 1,
  navId: 1,
  appId: 1,
  categoryId: 0,
  title: '',
  github: '',
  gitee: '',
  homepage: '',
  author: '',
  summary: '',
  tags: '',
  coverUrl: '',
  md: '',
  html: '',
  content: '',
  version: 3,
  status: 1,
})
const backend = ref()
const rules = reactive<any>({
  title: [{ required: true, trigger: 'blur', message: '请输入模板名称' }],
  author: [{ required: true, trigger: 'blur', message: '请输入作者' }],
  tags: [{ required: true, trigger: 'blur', message: '请选择UI组件' }],
  coverUrl: [{ required: true, trigger: 'change', message: '请上传封面图' }],
})
const formRef = ref<FormInstance>()
const drawer = ref(false)
const activeCollapse = ref(['1', '2', '3', '4'])
const isEdit = ref(false)
const route = useRoute()
const state = reactive<any>({
  // 标签列表
  tagList: [],
  // 后台语言列表
  backendList: [],
})

const showDrawer = () => {
  set(drawer, true)
}

const onChangeMd = (v: string) => {
  modelForm.md = v
}

// 获取详情
const getDetail = async (id: number) => {
  const data: any = await fetchArticle({ id })

  data.version = +data.version
  data.tags = data.tags?.map((tag: any) => tag.id)
  document.title = data.title

  Object.assign(modelForm, data)
}

const init = () => {
  route.query.nav_id && (modelForm.navId = +route.query.nav_id)

  if (route.query.id) {
    modelForm.id = +route.query.id
    getDetail(modelForm.id)
    set(isEdit, true)
  } else {
    document.title = `新增 - ${ProjectName}`
  }
}

init()
// 获取列表
const getTags = async () => {
  const { rows }: any = await fetchTagsData({ params: { type: 1 } })
  state.tagList = rows
}

getTags()

// 后台语言列表
const getBackend = async () => {
  const { rows }: any = await fetchBackendData({ params: { type: 1 } })
  state.backendList = rows
}

getBackend()

// 取消
const handleCancel = () => {
  handleClose()
}

// 关闭
const handleClose = () => {
  set(drawer, false)
}

const handleMessage = (data: any) => {
  for (const p of Object.keys(data)) {
    notificationError(data[p]?.message)
  }
}

// 提交前进行业务处理
const handleModelForm = (modelForm: any) => {
  modelForm.content = modelForm.html
  modelForm.tags = state.tagList.filter((tag: any) => modelForm.tags.includes(tag.id))
  modelForm.backend = state.backendList.filter((back: any) => backend.value === back.id)

  return modelForm
}

// 提交
const onSave = () => {
  formRef
    .value!.validate((valid: any) => {
      if (valid) {
        handleMessage(valid)
        return
      }

      const data = unref(handleModelForm(modelForm))

      if (!data.github && !data.gitee) {
        notificationError('请输入仓库地址')
        return
      }

      onSubmit(data)
    })
    .catch((error: any) => {
      console.log('error', error)
    })
    .finally(() => {})
}

// 新增
const createData = (data: any) => {
  fetchArticle({ type: 'post', params: data }).then((res) => {
    res && handleSuccess()
  })
}

// 修改
const updateData = (data: any) => {
  fetchArticle({ id: data.id, type: 'patch', params: data }).then((res: any) => {
    res ? handleSuccess() : notificationError(res?.error || '操作失败，请稍候在试~！')
  })
}

const onSubmit = (data: any) => {
  isEdit.value ? updateData(data) : createData(data)
}

// 处理成功
const handleSuccess = () => {
  notificationSuccess('操作成功，页面正在跳转中')
  formRef.value!.resetFields()

  setTimeout(() => {
    window.location.reload()
  }, 500)
}
</script>
<template>
  <div class="app-page-md-edit">
    <a-form ref="formRef" class="app-md-form" :model="modelForm" auto-label-width :rules="rules">
      <div class="app-md-header">
        <div class="app-md-title">
          <a-form-item label="标题" field="title">
            <a-input v-model="modelForm.title" :max-length="100" show-word-limit autocomplete="off" placeholder="请输入标题，您可以输入100个字" class="title-input" />
          </a-form-item>
        </div>
        <div class="app-md-action">
          <a-button class="app-md-btn" type="primary" @click="showDrawer()">发布</a-button>
        </div>
      </div>
      <div id="editor" class="app-md-editor markdown-body">
        <MarkDownEditor v-model="modelForm.html" :content="modelForm.md" @change="onChangeMd" />
      </div>
      <a-drawer :visible="drawer" :width="575" @ok="onSave" @cancel="handleCancel" unmount-on-close class="app-md-drawer-wrap">
        <div class="app-md-drawer">
          <a-collapse :default-active-key="activeCollapse" class="app-aside-collapse">
            <a-collapse-item header="版本" key="1">
              <a-row class="app-row-version">
                <a-col :span="10">
                  <a-form-item field="version" hide-label>
                    <a-radio-group v-model="modelForm.version">
                      <a-radio :value="3" size="large">Vue3</a-radio>
                      <a-radio :value="2" size="large">Vue2</a-radio>
                    </a-radio-group>
                  </a-form-item>
                </a-col>
                <a-col :span="14">
                  <a-form-item label="UI组件" field="tags">
                    <a-select v-model="modelForm.tags" multiple :limit="1" class="w-full" placeholder="请选择UI组件">
                      <a-option v-for="item in state.tagList" :key="item.id" :label="item.tagName" :value="item.id" />
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>
            </a-collapse-item>

            <a-collapse-item header="文章信息" key="2">
              <a-form-item label="应用" field="appId">
                <MyApp v-model="modelForm.appId" :style="{ width: '100%' }" />
              </a-form-item>
              <a-row :gutter="20" class="mb-5">
                <a-col :span="12">
                  <a-form-item label="类别" field="navId">
                    <a-select v-model="modelForm.navId" :limit="1" class="w-full" placeholder="请选择分类">
                      <a-option label="Admin" :value="1" />
                      <a-option label="UI组件库" :value="2" />
                      <a-option label="Hooks" :value="3" />
                    </a-select>
                  </a-form-item>
                </a-col>
                <a-col :span="12">
                  <a-form-item label="后台语言" field="backend">
                    <a-select v-model="backend" class="w-full" placeholder="请选择语言">
                      <a-option v-for="item in state.backendList" :key="item.id" :label="item.backendName" :value="item.id" />
                    </a-select>
                  </a-form-item>
                </a-col>
              </a-row>
              <a-form-item label="Github" field="github">
                <a-input v-model="modelForm.github" placeholder="请输入Github" />
              </a-form-item>
              <a-form-item label="Gitee" field="gitee">
                <a-input v-model="modelForm.gitee" placeholder="请输入Gitee" />
              </a-form-item>
              <a-form-item label="主页" field="homepage">
                <a-input v-model="modelForm.homepage" placeholder="请输入主页" />
              </a-form-item>
              <a-form-item label="作者" field="author">
                <a-input v-model="modelForm.author" placeholder="请输入作者" />
              </a-form-item>
            </a-collapse-item>

            <a-collapse-item header="简介" key="3">
              <a-form-item field="description" hide-label>
                <a-textarea v-model="modelForm.summary" :autosize="{ minRows: 2, maxRows: 4 }" :max-length="100" allow-clear show-word-limit placeholder="请输入简介" />
              </a-form-item>
            </a-collapse-item>

            <a-collapse-item header="封面图" key="4" class="app-collapse-cover">
              <a-form-item field="coverUrl" hide-label>
                <AppUpload id="cover1" v-model:imageUrl="modelForm.coverUrl">
                  <template #tip> 只能上传jpg/png文件，且不超过2MB </template>
                </AppUpload>
              </a-form-item>
            </a-collapse-item>
          </a-collapse>
        </div>
      </a-drawer>
    </a-form>
  </div>
</template>
<style lang="scss">
body {
  background: #fff !important;
}
.app-page-admin {
  border: 1px slid #ccc;
}
.app-md-header {
  line-height: 70px;
  padding: 0 20px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  .arco-form-item-content {
    margin-right: 20px;
  }
}
.app-md-title {
  flex: 1;
  line-height: 30px;
  .arco-form-item {
    margin-bottom: 0 !important;
  }
  .arco-form-item-message {
    position: absolute;
    top: 50px;
  }
}
.app-md-title .title-input {
  width: 100%;
}
.app-md-title .title-input input {
  border: 0;
  box-shadow: none;
}
.app-md-editor {
  width: 100%;
}
.app-aside-collapse {
  .arco-collapse-item-content-box {
    padding: 20px 0;
  }
  .arco-collapse-item-content {
    background-color: #fff;
  }
}
</style>
